<?php

namespace common\models;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "Coupon".
 */
class Coupon extends ActiveRecord {
    
    // 优惠劵状态
    const StatusActive = 0;
    const StatusDisable = 1;
    public static $statusSelector = [
        self::StatusActive => ['title' => '已激活', 'status' => 'green'],
        self::StatusDisable => ['title' => '已禁用', 'status' => 'red'],
    ];
    
    // 优惠劵类型
    const TypeEmployment = 1;
    public static $typeSelector = [
        self::TypeEmployment => ['title' => '雇佣抵扣劵', 'status' => 'blue'],
    ];
    
    // 优惠方式
    const ModeFullCut = 1;
    const ModeDiscount = 2;
    public static $modeSelector = [
        self::ModeFullCut => ['title' => '满减', 'status' => 'blue'],
        self::ModeDiscount => ['title' => '折扣', 'status' => 'red'],
    ];
    
    // 过期方式
    const TimeoutNever = 1;
    const TimeoutFixed = 2;
    const TimeoutByDay = 3;
    public static $timeoutSelector = [
        // self::TimeoutNever => ['title' => '永不过期', 'status' => 'green'],
        self::TimeoutFixed => ['title' => '固定日期', 'status' => 'gray'],
        self::TimeoutByDay => ['title' => '天数', 'status' => 'blue'],
    ];
    
    
    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['title', 'type', 'timeout', 'mode', 'mode_value', 'status'], 'required'],
            [['type', 'timeout', 'mode', 'status', 'deleted_at'], 'integer'],
            [['mode_value'], 'double'],
            [['title', 'timeout_value'], 'string', 'max' => 32],
            [['describe'], 'string', 'max' => 1024],
            [['remark'], 'string', 'max' => 255],
        ];
    }
    
    /**
     * 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            'type' => '类型',
            'timeout' => '过期方式',
            'timeout_value' => '过期周期',
            'mode' => '优惠方式',
            'mode_value' => '优惠额度',
            'describe' => '描述',
            'remark' => '备注',
            'status' => '状态',
            'deleted_at' => '删除时间'
        ];
    }
    
    /**
     * 数据校验规则
     * @param $type string 校验方式
     * @return array
     */
    public static function flyer($type = 'insert')
    {
        return [
            'param' => [
                'title' => ['标题', ['maxlength' => 32, 'required']],
                'type' => ['类型', ['inkey' => static::$typeSelector, 'required']],
                'timeout' => ['过期方式', ['inkey' => static::$timeoutSelector, 'required']],
                'timeout_value' => ['过期周期', ['int', 'required']],
                'mode' => ['优惠方式', ['inkey' => static::$modeSelector, 'required']],
                'mode_value' => ['优惠额度', ['float', 'required']],
                'describe' => ['描述', ['maxlength' => 1024, 'required']],
                'remark' => ['备注', ['maxlength' => 255]],
            ],
            'relate' => [
                // [[['timeout', 'in', [(string)static::TimeoutFixed, (string)static::TimeoutByDay]]], ['timeout_value']],
                [[['timeout', 'eq', static::TimeoutFixed]], ['timeout_value' => ['rule' => ['date' => 'Y-m-d', 'required']]]],
                // [[['timeout', 'eq', static::TimeoutByDay]], ['timeout_value' => ['rule' => ['int', 'required']]]],
            ]
        ];
    }
    
    /**
     * 获取限制条件
     * @return mixed
     */
    public function getConfigurations()
    {
        return $this->hasMany(CouponConfiguration::className(), ['coupon_id' => 'id']);
    }
    
    /**
     * 判断优惠劵是否可用
     * @param $order array 优惠计算参数
     * @return boolean
     */
    public function usable($order)
    {
        if(empty($this->configurations)) {
            return false;
        }
        /** @var CouponConfiguration $configuration */
        foreach($this->configurations as $configuration) {
            if( ! $configuration->usable($order)) {
                return false;
            }
        }
        return true;
    }
    
    /**
     * 判断是否可领取
     * @return boolean
     */
    public function receive()
    {
        if($this->deleted()) {
            return false;
        }
        if( ! in_array($this->status, [static::StatusActive])) {
            return false;
        }
        return true;
    }
    
    /**
     * 计算减免金额
     * @param $params array 优惠计算参数
     * @return integer
     */
    public function deduct($params = [])
    {
        $deduct = 0;
        if( ! isset($params['amount'])) {
            return $deduct;
        }
        // 根据优惠方式，计算优惠金额
        switch($this->mode) {
            case static::ModeFullCut: {
                $deduct = $this->mode_value;
            } break;
            case static::ModeDiscount: {
                $deduct = bcdiv(bcmul($params['amount'], $this->mode_value, 0), 100, 0);
            } break;
        }
        return $deduct;
    }
    
    /**
     * 保存优惠劵
     * @param $configurations array list of coupon configuration params
     * @return boolean
     */
    public function tsave($configurations)
    {
        return $this->transaction(function($db) use ($configurations) {
            if( ! $this->save()) {
                throw new \Exception('update coupon error');
            }
            if( ! $this->saveConfigurations($configurations)) {
                throw new \Exception('update coupon configurations error');
            }
            return true;
        });
    }
    /**
     * 保存用户分类
     * @param $name string checkbox名称
     * @param $type int 上传类型
     * @return boolean
     */
    public function saveConfigurations($configurations)
    {
        if( ! empty($this->configurations)) {
            if( ! CouponConfiguration::deleteAll(['id' => ArrayHelper::index($this->configurations, 'id')])) {
                return false;
            }
        }
        foreach($configurations as $configuration) {
            $params[] = [
                'coupon_id' => $this->id,
                'condition' => $configuration['condition'],
                'operate' => $configuration['operate'],
                'threshold' => $configuration['threshold'],
                'created_at' => time(),
                'updated_at' => time(),
            ];
        }
        return CouponConfiguration::batchInsert($params);
    }
    
    /**
     * 优惠额度展示
     * @param $coupon array 优惠劵
     * @return string
     */
    public static function deductText($coupon)
    {
        $modeValue = '';
        switch($coupon['mode']) {
            case static::ModeFullCut: {
                $modeValue = '￥'.bcdiv($coupon['mode_value'], 100, 0);
            } break;
            case static::ModeDiscount: {
                $discount = bcsub(100, $coupon['mode_value']);
                for($i = 0; $i < strlen($discount); ++$i) {
                    $string = [
                        '1' => '一', '2' => '二', '3' => '三', '4' => '四', '5' => '五',
                        '6' => '六', '7' => '七', '8' => '八', '9' => '九',
                    ];
                    if($discount[$i] == 0) {
                        continue;
                    }
                    $modeValue .= $discount[$i];
                }
                if($discount < 10) {
                    $modeValue = '零点'.$modeValue;
                }
                $modeValue .= '折';
            } break;
            default: {
                $modeValue = '异常劵';
            }
        }
        return $modeValue;
    }
}
